<template>
	<a-modal :visible="visible" width="550px" title="接受预定" centered destroyOnClose @cancel="cancel" :footer="null" :maskClosable="false" :bodyStyle="{padding: 0}">
		<div v-if="detailInfo.isAlreadyBook" class="failure-box">
			<ExclamationCircleFilled v-color="{color: COLOR_MAP.orange}" />
			<span v-color="{color: COLOR_MAP.orange}" class="failure-reason">
				<span>该申请的房源已被预定,请与预定人重新确认新的预定房源。</span>
			</span>
		</div>
		<div class="flex-container-nomal" style="max-height: 70vh">
			<div class="flex1 auto-y">
				<a-space :size="24" direction="vertical">
					<a-descriptions size="small" :contentStyle="{justifyContent: 'flex-end'}">
						<!-- /{{ sexList[detailInfo.gender] }} -->
						<a-descriptions-item label="预定人信息" :span="3">{{ detailInfo.name }}/{{ detailInfo.phone }}</a-descriptions-item>
						<a-descriptions-item label="预定房源" :span="3">
							<template #title>
								<span>
									<span v-if="detailInfo.isAlreadyBook">原</span>
									预定房源
								</span>
							</template>

							{{ detailInfo.houseAddress }}
						</a-descriptions-item>
						<a-descriptions-item v-if="detailInfo.isAlreadyBook" label="新预定房源" :span="3">
							<a-select v-model:value="modelRef.houseId" v-bind="searchOptions" size="small" style="flex: 1">
								<template v-if="loadings.search" #notFoundContent>
									<a-spin spinning tip="正在搜索，请稍候……" />
								</template>
							</a-select>
						</a-descriptions-item>
						<a-descriptions-item label="最晚签约日期" :span="3">
							<a-date-picker style="width: 200px" v-model:value="modelRef.signDate" placeholder="请选择最晚签约日期" :value-format="DATE_FORMAT.DATE" size="small" :disabledDate="disabledDate" :allowClear="false" />
							<!-- {{ formatDate(detailInfo.signDate) }} -->
						</a-descriptions-item>
						<a-descriptions-item label="定金" :span="3">{{ detailInfo.money }}元</a-descriptions-item>
						<a-descriptions-item label="备注" :span="3">{{ detailInfo.comment }}</a-descriptions-item>
					</a-descriptions>
					<div></div>
				</a-space>
			</div>
			<div class="a-modal-dialog-footer">
				<a-space :size="12">
					<a-space :size="12">
						<a-button @click="cancel">取消</a-button>
						<a-button type="primary" :loading="loading" :disabled="loading" @click="run">确定</a-button>
					</a-space>
				</a-space>
			</div>
		</div>
	</a-modal>
</template>
<script setup lang="ts">
	import {ref, watch, reactive, onMounted} from 'vue'
	import {useRequest} from 'vue-request'
	import {bookConfirm, getBookDetail, searchByAddress, getHouseBookRule} from '@/api/contract'
	import {message} from 'ant-design-vue'
	import {sexList} from '@/utils'
	import {formatDate} from 'yuxin-base/src/utils/date'
	import {ExclamationCircleFilled} from '@ant-design/icons-vue'
	import XEUtils from 'xe-utils'
	import DATE_FORMAT from 'yuxin-base/src/utils/date'
	import dayjs, {Dayjs} from 'dayjs'
	import {COLOR_MAP} from 'yuxin-base/src/constant'

	const props = defineProps({
		visible: {
			type: Boolean,
			required: true
		},
		id: {
			type: [String, Number],
			default: ''
		}
	})
	const maxDate = ref<any>('')
	const emit = defineEmits(['update:visible', 'success'])

	const modelRef = reactive<any>({
		houseId: null,
		houseAddress: null,
		signDate: null
	})

	const loadings = reactive({
		save: false,
		search: false
	})

	const cancel = () => {
		emit('update:visible', false)
		detailInfo.value = {}
	}
	watch(
		() => props.visible,
		(newVal: boolean) => {
			if (newVal) {
				modelRef.houseId = null
				modelRef.houseAddress = null
				getDetail()
			}
		}
	)

	const detailInfo = ref<any>({})
	const getDetail = () => {
		getBookDetail(props.id).then((res: any) => {
			detailInfo.value = res.data
		})
	}

	const sendRequest = () => {
		let params = {
			id: props.id,
			endSignDate: modelRef.signDate,
			houseId: modelRef.houseId
		}

		return bookConfirm(params)
	}

	const disabledDate = (current: any) => {
		let beginTime = dayjs(new Date()).format(DATE_FORMAT.DATE)
		return current.isBefore(beginTime, 'day') || current.isAfter(maxDate.value, 'day')
	}

	const {run, loading} = useRequest(sendRequest, {
		manual: true,
		formatResult: (res: any) => {
			message.success('操作成功')
			let temp = setTimeout(() => {
				emit('success')
				clearTimeout(temp)
			}, 300)
			cancel()
		}
	})

	// 房源搜索结果
	const houseData = ref<any[]>([])
	const maxAmount = ref<number>(0)
	const getPreBookDays = ref(null)
	const isMoneyDisabled = ref(false)
	const searchOptions = reactive<any>({
		options: houseData,
		showSearch: true,
		filterOption: false,
		placeholder: '请输入房源地址进行搜索',
		fieldNames: {
			label: 'address',
			value: 'houseRoomId'
		},
		onSearch(like: string) {
			if (!like && !like.trim()) {
				return
			}

			handleSearch(like)
		},
		onSelect(value: string, option: any) {
			handleChange(value, option)
		}
	})

	const handleSearch = XEUtils.debounce((like: string) => {
		let params = {
			houseType: 0,
			like,
			current: 1,
			bizType: 3,
			size: 9999,
			hasHouseType: true,
			statusInCondition: [11],
			preBookDays: getPreBookDays.value
		}

		loadings.search = true
		searchByAddress(params)
			.then((res: any) => {
				houseData.value = res.data.records
			})
			.finally(() => (loadings.search = false))
	}, 300)

	const handleChange = (value: string, option: any = {}) => {
		if (!value) {
			houseData.value = []
		}
		modelRef.houseId = value
		modelRef.houseAddress = option.address
		modelRef.housePid = option.houseBaseId
		modelRef.maintainerId = option.houseMaintainersId
		if (maxAmount.value && option.actualPrice) {
			modelRef.money = XEUtils.multiply(XEUtils.multiply(maxAmount.value, option.actualPrice), 0.01)
		} else {
			modelRef.money = modelRef.money || 0
		}
		isMoneyDisabled.value = modelRef.money ? true : false
		// maxAmount.value = option.actualPrice
	}
	onMounted(() => {
		houseBookRule()
	})

	const houseBookRule = async () => {
		getHouseBookRule().then(res => {
			modelRef.signDate = dayjs(new Date())
				.add(res.data?.day - 1 || 0, 'day')
				.format(DATE_FORMAT.DATE)
			maxDate.value = dayjs()
				.add(res.data?.day - 1, 'day')
				.format(DATE_FORMAT.DATE)
		})
	}
</script>
<style lang="less" scoped>
	.failure-box {
		height: 30px;
		background: #fffbe6;
		border-radius: 2px 2px 2px 2px;
		opacity: 1;
		border: 1px solid #ffe58f;
		padding-left: 10px;
		margin: 10px 12px 10px 12px;
		font-size: 12px;
		.failure-reason {
			margin: 3px 5px;
			line-height: 30px;
		}
	}
</style>
